#include "myUDP.h"

#include <QTimer>

myUDP::myUDP()
{
    qDebug()<<"hi";

    ready2send = false;
    packet_testing = false;

    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress("127.0.0.1"), 2000);
    //udpSocket->bind(2000);
    connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readCmd()));

//    QTimer *taskTimer = new QTimer;
//    taskTimer->start(200);
//    connect(taskTimer, SIGNAL(timeout()), this, SLOT(sendResult()));
}

myUDP::~myUDP()
{
    qDebug()<<"bye";
}

void myUDP::run()
{
    exec();
}

void myUDP::sendResult(char* buff, int size)
{
    QHostAddress hostaddr;
    hostaddr.setAddress( "127.0.0.1" );

    udpSocket->writeDatagram(buff, size, hostaddr, 1999);

//    if(ready2send)
//    {
//        udpSocket->writeDatagram( sendBuf, hostaddr, 1999);
//        ready2send = false;
//        sendBuf.resize(0);
//    }

    //qDebug()<<"taskTimer";
}

void myUDP::readCmd()
{
    qDebug()<<"new coming!";

    QByteArray rcvd;

    if( udpSocket->hasPendingDatagrams() )
    {
        rcvd.resize(udpSocket->pendingDatagramSize());

        udpSocket->readDatagram(rcvd.data(), rcvd.size());
    }

    char *ch = rcvd.data();

    if( memcmp(ch, "start", 5) == 0 )
    {
        packet_testing = true;
    }

    if( memcmp(ch, "stop", 4) == 0 )
    {
        packet_testing = false;
    }

    emit startOrStop(packet_testing);
}
